<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../../node_modules/axios/dist/axios.min.js"></script>
</head>
<body>
    <script>
        const userAxios = axios.create({
            baseURL:"http://localhost:8888",
            timeout:10000 //超时时间  10s
        })
        const getToken = ()=>localStorage.getItem('token');
        const removeToken = ()=>localStorage.removeItem('token');
        const removeUserInfo = ()=>sessionStorage.removeItem('userInfo');

        //请求拦截器
        userAxios.interceptors.request.use(config=>{

            let token = getToken();

            //设置请求头 - 将token携带到headers内部
            if(token){
                config.headers.token = token;
            }

            return config;
        });


        // 响应拦截器
        userAxios.interceptors.response.use(res=>{
            // 进度条关闭
            return res.data;
        },rea=>{
            //请求响应失败 - 执行到这里
            //进度条关闭
            // console.log(rea);
            // console.log(rea.response.status);

            if(rea.response.status===401){
                removeToken();

                removeUserInfo();

                alert('token非法或无效');

                // window.location.href = '/login.html';
            }

            //向下传递错误
            throw rea;
        })

        userAxios('/admin/info').then(val=>{
            console.log(val);
        },rea=>{
            console.log(rea);
        })
    </script>
</body>
</html>